<template>
  <view>
    <uv-upload :fileList="fileList" multiple :disabled="disabled" :maxCount="1" @afterRead="afterRead"
      @delete="deletePic" :width="`${width}rpx`" :height="`${height}rpx`" :previewFullImage="false">
      <image :src="uploadImg" mode="aspectFit" :style="{width: width+'rpx',height: height+'rpx'}"></image>
    </uv-upload>
  </view>
</template>

<script>
  export default {
    props: {
      disabled: {
        type: Boolean,
        default: false
      },
      uploadImg: {
        type: String,
        default: ""
      },
      keyName: {
        type: String,
        default: ""
      },
      width: {
        type: Number,
        default: 160
      },
      height: {
        type: Number,
        default: 160
      }
    },
    data() {
      return {
        fileList: []
      }
    },
    onReady() {
      console.log("uploadImg", this.uploadImg);
      if (this.uploadImg) {
        this.fileList.push({
          url: this.uploadImg
        })
      }
    },
    methods: {
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1);
      },
      // 新增图片
      async afterRead(event) {
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          const info = JSON.parse(result);
          console.log("上传图片", info.data.url);
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: info.data.url
          }))
          fileListLen++
        }
        console.log("fileList", this.fileList);
        let str = this.fileList.map(v => v.url);
        let value = str.join(",");
        console.log("处理过的url", value);
        // this.$emit("update:modelValue", temp);
        this.$emit("getUrl", {
          keyName: this.keyName,
          value
        });
      },
      uploadFilePromise(url) {
        console.log("图片路径", url);
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: this.baseUrl + "/api/upload/image",
            filePath: url,
            name: "file",
            formData: {
              user: "test",
            },
            header: {
              "Authorization": 'Bearer ' + uni.getStorageSync("token"), //自定义请求头信息
            },
            success: (res) => {
              setTimeout(() => {
                resolve(res.data);
              }, 1000);
            },
          });
        });
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>